export function flattenTree(tree = [], childKey = 'children') {
  return tree.reduce((acc, node) => {
    // 如果当前节点有子节点，则递归调用flattenTree并将结果合并到累加器

    // 将当前节点添加到累加器中
    if (node[childKey] && node[childKey].length > 0) {
      acc.push(...flattenTree(node[childKey], childKey))
    }

    acc.push(node)
    return acc
  }, [])
}

// 递归累加
export function childRecursion(curNode, countObj) {
  const dataCount = countObj[curNode.id] || { personnelCount: 0, carCount: 0 }
  // 深度遍历
  if (curNode.children) {
    curNode.children.forEach((node) => {
      if (!node.count) node.count = {}

      const child = childRecursion(node, countObj)
      dataCount.personnelCount = dataCount.personnelCount + child.personnelCount
      dataCount.carCount = dataCount.carCount + child.carCount
    })
  }

  curNode.count = dataCount
  return dataCount
}

/**
 * @param {Number} len uuid的长度
 * @param {Boolean} firstU 将返回的首字母置为"u"
 * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
 */
export function guid(len = 32, firstU = true, radix = null) {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []
  radix = radix || chars.length

  if (len) {
    // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
    for (let i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    let r
    // rfc4122标准要求返回的uuid中,某些位为固定的字符
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    for (let i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
  if (firstU) {
    uuid.shift()
    return `u${uuid.join('')}`
  }
  return uuid.join('')
}
